package com.intelligent.health.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intelligent.health.base.excption.FileExportException;
import com.intelligent.health.base.export.ExportInterfaceService;
import com.intelligent.health.base.utils.PageUtil;
import com.intelligent.health.base.utils.SpringUtil;
import entity.constant.ExceptionConst;
import entity.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/03/26/1:08
 * @Description: 文件导入导出控制器
 */
@Slf4j
@RestController
@RequestMapping("/base")
public class FileExportController {

    private static final Integer CURRENT_PAGE = 0;
    private static final Integer END_PAGE = 1;
    private static final Integer PAGE_SIZE = 5;

    /**
     * 导出Excel表格
     *
     * @param impl 接口名
     * @param response 相应结果
     * @param hashMap 结果集合
     * @throws Exception 异常
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    @PostMapping("/api/export/{impl}")
    public void exportUser(@PathVariable("impl") String impl,
                           HttpServletResponse response,
                           @RequestBody HashMap<String, Object> hashMap) throws Exception {
        if (hashMap.get("pageInfo") == null) {
            PageInfo pageInfo = new PageInfo();
            pageInfo.setCurrentPage(CURRENT_PAGE);
            pageInfo.setEndPage(END_PAGE);
            pageInfo.setPageSize(PAGE_SIZE);
            hashMap.put("pageInfo", pageInfo);
        } else {
            PageInfo pageInfo = JSONObject.parseObject(JSON.toJSONString(hashMap.get("pageInfo")), PageInfo.class);
            if (pageInfo.getCurrentPage() <= 0 || pageInfo.getEndPage() <= 0 || pageInfo.getCurrentPage() > pageInfo.getEndPage()) {
                throw new FileExportException(ExceptionConst.PARAM_EMPTY);
            } else {
                pageInfo.setStartRowNum(PageUtil.getStartRowNum(pageInfo.getPageSize(), pageInfo.getCurrentPage()));
                pageInfo.setEndRowNum(PageUtil.getEndRowNum(pageInfo.getPageSize(), pageInfo.getEndPage()));
            }
            hashMap.put("pageInfo", pageInfo);
        }
        System.out.println(hashMap);
        ExportInterfaceService exportInterfaceService = (ExportInterfaceService) SpringUtil.getBean(impl);
        exportInterfaceService.getExportBeanList(hashMap, response);
    }
}
